package demo;

import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

public class ClassPathXmlApplicationContext implements BeanFactory {

    private Map<String, Object> container = new HashMap<>();

    // 加载配置文件并初始化Bean对象
    public ClassPathXmlApplicationContext(String fileName) throws Exception {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        DocumentBuilder builder = factory.newDocumentBuilder();
        Document doc = builder.parse(this.getClass().getClassLoader()
                .getResourceAsStream(fileName));

        NodeList beanList = doc.getElementsByTagName("bean");
        for (int i = 0; i < beanList.getLength(); i++) {
            Node node = beanList.item(i);
            NamedNodeMap namedNodeMap = node.getAttributes();
            String id = namedNodeMap.getNamedItem("id").getNodeValue();
            String className = namedNodeMap.getNamedItem("class").getNodeValue();

            // 创建对象并放入容器中
            Object obj = Class.forName(className).newInstance();
            container.put(id, obj);

            // 注入对象属性
            NodeList propertyList = node.getChildNodes();
            for (int j = 0; j < propertyList.getLength(); j++) {
                Node propertyNode = propertyList.item(j);
                if ("property".equals(propertyNode.getNodeName())) {
                    String propertyName =
                            propertyNode.getAttributes().getNamedItem("name").getNodeValue();
                    String propertyRef =
                            propertyNode.getAttributes().getNamedItem("ref").getNodeValue();
                    Object propertyObj = container.get(propertyRef);

                    Method[] methods = obj.getClass().getMethods();
                    for (Method method : methods) {
                        if (method.getName().equalsIgnoreCase("set" + propertyName)) {
                            method.invoke(obj, propertyObj);
                            break;
                        }
                    }
                }
            }
        }
    }

    @Override
    public Object getBean(String name) {
        return container.get(name);
    }
}
